#!/usr/bin/perl
################################################################
#         GoogleTranslation version 0.1
#     Translate input files from source language to target language by Google
#     Translation(Web).
#
#     usage: perl GoogleTranslation.pl [file1 file2 ...] >[output file]
#
#   Written by He Wei.
#   The file is created on July 31, 2007.
################################################################
use strict;
use LWP;
my $lang = "zh-CN|en";   # "source_language|target_language"
                      # You can change $lang to the lauguage code you want.
                      # (es = Spanish, en = English, zh-CN = Simplified Chinese, ...)
my $delay_time = 0;  #seconds
my $ua = LWP::UserAgent->new;
my $output="";

$ua->agent("GoogleTranslation/0.1");
my $url = 'http://translate.google.com/translate_t';
while(<>) {
  chomp;

  $_ =~ s/\r//sg; 
  $_ =~ s/^\s+//sg; 
  $_ =~ s/\s+$//sg; 
  
  if ($_ =~ /^*\\/){
   print "$_\n";
   print STDERR 'o'; 
   next;  
  }
  if ($_ =~ /^*%/){
    print "$_\n";
    print STDERR '%';
    next;
  }
  if ($_ =~ /^$/ ){
    print "$_\n";
    print STDERR '`';
    next;
  }
  
  my $res = $ua->post( $url,
      [ 'hl' => 'en',
        'ie' => 'UTF8',
        'text' => $_,
        'langpair' => $lang,
      ]
  );
  die "$url error: ", $res->status_line
    unless $res->is_success;
  if( $res->content =~ /<textarea.*? id=suggestion>(.*?)<\/textarea>/ ) {
      $output = $1;
      $output =~ s/.amp..[0-9][0-9]./\s/sg; 
#      $output =~ s/\{/\(/g;
#      $output =~ s/\}/\)/g;
      print "$output\n";
      print STDERR "$_.";
      print STDERR "$output,";
  }
}
